package com.want.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Optional;
import java.util.function.Predicate;

/**
 * @author WangZhiJian
 * @since 2021/11/19
 */
@EnableOpenApi
public class SwaggerConfiguration {
    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired(required = false)
    @Qualifier("annotationsSelectors")
    private Predicate<RequestHandler> annotationsSelectors;

    /**
     * 构建swagger文档实体
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(Docket.class)
    public Docket groupRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(groupApiInfo())
                .select()
                .apis(Optional.ofNullable(annotationsSelectors).map(s -> s.and(classNameSelectors())).orElse(classNameSelectors()))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 进行api的过滤，只保留项目内部的api
     * @return
     */
    private Predicate<RequestHandler> classNameSelectors(){
        return input -> Optional.ofNullable(input.groupName())
                .map(this::validateClassName)
                .orElse(false);
    }

    /**
     * 移除以下组别的swagger文档
     * @param groupName
     * @return
     */
    private Boolean validateClassName(String groupName){
        boolean flag = groupName.equals("operation-handler")
                || groupName.equals("web-mvc-links-handler")
                || groupName.equals("bcl-error-controller");
        return !flag;
    }

    /**
     * api的部分信息
     * @return
     */
    private ApiInfo groupApiInfo(){
        return new ApiInfoBuilder()
                .title(applicationName+"文档地址")
                .description("<div style='font-size:14px;color:red;'>"+applicationName+"文档地址</div>")
//                .version("3.0")
                .build();
    }
}
